#include "r1_dir.h"
#include "mpx_supt.h"

#define DEFAULT_DIRECTORY "."
#define DISPLAY_AT_A_TIME 10
#define FILENAME_BUFFER_SIZE 256

void displayMPX_printErrorMessage(code) {
	switch (code) {
	case ERR_SUP_DIROPN:
		printf("\nError: could not open directory \"%s\".\n\n", directory);
		break;

	case ERR_SUP_INVDIR:
		printf("\nError: \"%s\" is an invalid directory.\n\n", directory);
	}
}

int displayMPX(int argc, char **args) {
	char *directory;
	int  result;

	const char *newline      = "\n\n\0";
	const char *none         = "No .MPX files were found in the directory.\0";
	const char *prompt       = "Please press 'Enter' to continue. \0";
	const int  newlineLength = 2;
	const int  noneLength    = 42;
	const int  promptLength  = 34;

	// Attempt to open the user's requested directory.
	directory = (argc == 0 ? DEFAULT_DIRECTORY : args[0]);
	result = sys_open_dir(directory);

	// If the attempt succeeded, print the files in the directory and their
	// sizes to the standard output.
	if (result == OK) {
		char  dump[3] = {'\0'};
		char  filename[FILENAME_BUFFER_SIZE];
		char  output[FILENAME_BUFFER_SIZE * 2];
		int   dumpSize = 2;
		int   outputLength;
		int   written = 0;
		short pause = 0;
		long  fileSize;

		while (
			sys_get_entry(
				filename,
				FILENAME_BUFFER_SIZE,
				&fileSize
			) != ERR_SUP_NOENTR
		) {
			// If a specific number of lines have been printed, pause the
			// printing so the user can catch up.
			if (pause) {
				sys_req(WRITE, TERMINAL, prompt, &promptLength);
				sys_req(READ,  TERMINAL, dump,   &dumpSize);

				dump[0] = 0;
				dump[1] = wherey() - 2; // Does this work?
				dump[2] = '\0';

				sys_req(GOTOXY, TERMINAL, dump, &dumpSize);
				pause = 0;
			}

			// Write the file and its size to the terminal.
			outputLength = sprintf(
				output,
				"%s    %d bytes\n",
				filename,
				fileSize
			);
			sys_req(WRITE, TERMINAL, output, outputLength);

			// If a specific number of lines have been printed, set the pause
			// flag.
			if ((++written % DISPLAY_AT_A_TIME) == 0) {
				pause = 1;
			}
		}

		// If no files were printed, write a message to the screen.
		if (written == 0) {
			sys_req(WRITE, TERMINAL, none, &noneLength);
		}

		// Clear after the output.
		sys_req(WRITE, TERMINAL, newline, &newlineLength);
	}
	
	// Otherwise, print error messages explaining the failure.
	else {
		displayMPX_printErrorMessage(result);
	}

	// No errors should have gone unhandled, so return the success code.
	return OK;
}

int displayMPX_init() {
	return OK;
}

int displayMPX_exit() {
	return OK;
}